package com.daiqee.interceptor;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.daiqee.pojo.User;

/**
 * 记录用户使用系统内部资源拦截器
 * 
 * <br/>
 * @since JDK 1.8
 * @version  V2.1
 * @author RichardTang 
 * @date: 2018年5月7日 下午5:58:17
 * @package com.daiqee.interceptor
 * @copyright:Copyright (c) 2018, 1245811923@qq.com All Rights Reserved.
 */
public class OprLogInterceptor implements HandlerInterceptor {

	public static final Logger LOGGER = Logger.getLogger(OprLogInterceptor.class);  
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		HttpSession session = request.getSession();
		
		//如果没有session存在着可能非法登录也可能session过期
		if(session==null) {
			//没有session直接重定向到登录页面
			response.sendRedirect("/login.jsp");
			return false;
		}
		//从session中获取到当前用户
		User user = (User)session.getAttribute("user");
		//判断是否存在该用户
		if(user!=null) {
			//存在 添加到日志中,记录用户调用了什么接口
			LOGGER.info("\r当前使用账号:"+
			user.getUserName()+
			"\r接口:"+request.getRequestURI()+
			"请求类型:"+request.getMethod()+
			"\r控制器:"+handler.toString()
			);
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
